<?php
/**
 * @title 347. 前 K 个高频元素 - 哈希计数 + 最大堆
 * @author start2004
 */

class iMaxHeap extends SplMaxHeap{
    public function compare($arr1, $arr2)
    {
        if($arr1[1] == $arr2[1]){
            return 0;
        } elseif($arr1[1] > $arr2[1]) {
            return 1;
        } else {
            return -1;
        }
    }
}

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $k
     * @return Integer[]
     */
    function topKFrequent($nums, $k) {
        /**
         * @since 2020-07-30 哈希, 统计数量
         */
        $hashs = [];
        foreach ($nums as $num){
            if(isset($hashs[$num])){
                $hashs[$num] += 1;
            } else {
                $hashs[$num] = 1;
            }
        }

        /**
         * @since 2020-07-30 最大堆
         */
        $heap = new iMaxHeap();
        foreach ($hashs as $num=>$count){
            $heap->insert([$num, $count]);
        }

        /**
         * @since 2020-07-30 提取k个高频元素
         */
        $result = [];
        while($k > 0){
            list($num, $count) = $heap->extract();
            $result[] = $num;
            $k--;
        }

        /**
         * @return
         */
        return $result;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.30_5.php
 */
$datas = [
    [[1,1,1,2,2,3], 2],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->topKFrequent($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
